#!/usr/bin/env python3
"""
初始化同步功能权限
"""

import asyncio
import sys
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

from app.core.database import AsyncSessionLocal
from sqlalchemy import text

async def init_sync_permissions():
    """初始化同步功能权限"""
    
    # 同步功能权限配置
    permissions = [
        ('sync.view', '查看同步功能', '查看数据同步相关页面和信息', 'sync', 'view'),
        ('sync:task:view', '查看同步任务', '查看数据同步任务列表和详情', 'sync_task', 'view'),
        ('sync:task:create', '创建同步任务', '创建新的数据同步任务', 'sync_task', 'create'),
        ('sync:task:update', '更新同步任务', '修改数据同步任务配置', 'sync_task', 'update'),
        ('sync:task:delete', '删除同步任务', '删除数据同步任务', 'sync_task', 'delete'),
        ('sync:task:execute', '执行同步任务', '手动执行数据同步任务', 'sync_task', 'execute'),
        ('sync:execution:view', '查看执行记录', '查看数据同步执行记录和日志', 'sync_execution', 'view'),
        ('sync:execution:control', '控制执行过程', '暂停、恢复、取消同步任务执行', 'sync_execution', 'control'),
        ('sync:config:manage', '管理同步配置', '管理数据同步相关配置', 'sync_config', 'manage'),

    ]
    
    # 路由配置
    routes = [
        ('/sync', 'sync', '数据同步', '数据同步管理功能', 'SyncOutlined', 'SyncManagement', None, True, 5, True, True),
        ('/sync/tasks', 'sync_tasks', '同步任务', '数据同步任务管理', 'ScheduleOutlined', 'SyncTaskManagement', 1, True, 1, True, True),
        ('/sync/executions', 'sync_executions', '执行记录', '同步任务执行记录', 'HistoryOutlined', 'SyncExecutionMonitor', 1, True, 2, True, True),

    ]
    
    async with AsyncSessionLocal() as db:
        try:
            # 创建权限
            print("创建同步功能权限...")
            for name, display_name, description, resource, action in permissions:
                # 检查权限是否已存在
                result = await db.execute(text("""
                    SELECT id FROM dp_permissions WHERE name = :name
                """), {"name": name})
                
                if result.fetchone():
                    print(f"  权限已存在: {name}")
                    continue
                
                # 创建权限
                await db.execute(text("""
                    INSERT INTO dp_permissions (name, display_name, description, resource, action, created_at, updated_at)
                    VALUES (:name, :display_name, :description, :resource, :action, NOW(), NOW())
                """), {
                    "name": name,
                    "display_name": display_name,
                    "description": description,
                    "resource": resource,
                    "action": action
                })
                print(f"  创建权限: {name}")
            
            # 创建路由
            print("\n创建同步功能路由...")
            for path, name, display_name, description, icon, component, parent_id, is_menu, sort_order, is_active, is_system in routes:
                # 检查路由是否已存在
                result = await db.execute(text("""
                    SELECT id FROM dp_routes WHERE path = :path
                """), {"path": path})
                
                if result.fetchone():
                    print(f"  路由已存在: {path}")
                    continue
                
                # 创建路由
                await db.execute(text("""
                    INSERT INTO dp_routes (path, name, display_name, description, icon, component, parent_id, is_menu, sort_order, is_active, is_system, created_at, updated_at)
                    VALUES (:path, :name, :display_name, :description, :icon, :component, :parent_id, :is_menu, :sort_order, :is_active, :is_system, NOW(), NOW())
                """), {
                    "path": path,
                    "name": name,
                    "display_name": display_name,
                    "description": description,
                    "icon": icon,
                    "component": component,
                    "parent_id": parent_id,
                    "is_menu": is_menu,
                    "sort_order": sort_order,
                    "is_active": is_active,
                    "is_system": is_system
                })
                print(f"  创建路由: {path}")
            
            await db.commit()
            print("\n✅ 权限和路由初始化完成！")
            
            # 统计结果
            perm_result = await db.execute(text("""
                SELECT COUNT(*) FROM dp_permissions WHERE name LIKE 'sync%'
            """))
            perm_count = perm_result.scalar()
            
            route_result = await db.execute(text("""
                SELECT COUNT(*) FROM dp_routes WHERE path LIKE '/sync%'
            """))
            route_count = route_result.scalar()
            
            print(f"✅ 创建了 {perm_count} 个权限，{route_count} 个路由")
            
            return True
            
        except Exception as e:
            print(f"❌ 权限初始化失败: {e}")
            await db.rollback()
            return False

async def main():
    """主函数"""
    print("开始初始化同步功能权限...")
    success = await init_sync_permissions()
    
    if success:
        print("\n🎉 权限初始化完成！")
    else:
        print("\n❌ 权限初始化失败！")
        sys.exit(1)

if __name__ == "__main__":
    asyncio.run(main())
